/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Server;

import GUI.panelMensagens;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import javax.swing.JPanel;

import static Server.SocketMessengerConstants.*;



/**
 *
 * @author Gabriel
 */
public class MessengerServer extends Thread implements MessageListener {

    private ExecutorService serverExecutor; // executor for server
    private panelMensagens painelMensagens;

    public MessengerServer (panelMensagens painel)
    {
        painelMensagens = painel;
        
        }
   // start chat server
    @Override
   public void run()
   {
      // create executor for server runnables
      serverExecutor = Executors.newCachedThreadPool();

      try // create server and manage new clients
      {
         // create ServerSocket for incoming connections
         ServerSocket serverSocket =
            new ServerSocket( SERVER_PORT, 100 );

         painelMensagens.displayMessage("Bem vindo ao Simple Talk Server!\n");


         painelMensagens.displayMessage("\nServer listening on port " + SERVER_PORT + " ..." );
            

         // listen for clients constantly
         while ( true )
         {
            // accept new client connection
            Socket clientSocket = serverSocket.accept();

            // create MessageReceiver for receiving messages from client
            serverExecutor.execute(
               new MessageReceiver( this, clientSocket, painelMensagens ) );

            // print connection information
            painelMensagens.displayMessage( "\nConnection received from: " +
               clientSocket.getInetAddress() );
         } // end while
      } // end try
      catch ( IOException ioException )
      {
         ioException.printStackTrace();
      } // end catch
   } // end method startServer

   // when new message is received, broadcast message to clients
   public void messageReceived( String from, String message )
   {
      // create String containing entire message
      String completeMessage = from + MESSAGE_SEPARATOR + message;

      // create and start MulticastSender to broadcast messages
      serverExecutor.execute(
         new MulticastSender( completeMessage.getBytes() ) );
   } // end method messageReceived


}
